#include "pLayer.h"
#include "bits.h"
#include <cstring>
using namespace std;

/*
 * Indexing Functions
 */
int calc_pLayerIndex(int c, int i) {
	if(i == 0 || i == 63)
		return i;

	return ((c*i) % 63);
}

int pLayerIndex(int i) {
	return calc_pLayerIndex(16, i);
}

int inv_pLayerIndex(int i) {
	return calc_pLayerIndex(4, i);
}

/*
 * Permutations
 */
void permutate(int (*func)(int), unsigned char *dst) {
	int i, j;
	unsigned char src[8];

	// Init
	memcpy(src, dst, sizeof(char[8]));

	// Permutate
	for(i = 0; i < 64; ++i) {
		j = func(i);
		
		if(bitArrayGet(src, i) > 0)
			bitArraySet(dst, j);
		else
			bitArrayClear(dst, j);	
	}
}

void pLayer(unsigned char *state) {
	permutate(pLayerIndex, state);
}

void inv_pLayer(unsigned char *state) {
	permutate(inv_pLayerIndex, state);
}
